import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:gluz/app/common/bottom_modal_sheet.dart';
import 'package:gluz/app/common/extension/string_extension.dart';
import 'package:gluz/app/data/api_response.dart';
import 'package:gluz/app/data/area_entity.dart';
import 'package:gluz/app/modules/login/controllers/login_controller.dart';
import 'package:gluz/app/modules/login/register/controllers/register_controller.dart';
import 'package:gluz/app/utils/http_util.dart';
import 'package:gluz/app/utils/toast_util.dart';
import 'dart:io';

import '../../../../../app_session.dart';
import '../../../../common/aliyun_oss.dart';
import '../../../../common/resource_picker_sheet.dart';
import '../../../../data/country_entity.dart';
import '../../../../data/identity_entity.dart';
import '../../../../routes/app_pages.dart';

class RegisterInfoController extends GetxController {
  // 表单数据
  final registerController = Get.find<RegisterController>();
  final loginController = Get.find<LoginController>();
  final companyName = ''.obs;
  final userAvatar = Rx<String?>(null);
  final areaTextEditController = TextEditingController();
  final areaEntity = Rx<AreaEntity?>(null);
  final selectedIdentity = Rx<IdentityEntity?>(null); // IdentityEntity.dataSource().last.obs;

  // 身份选项
  final List<IdentityEntity> identityOptions = IdentityEntity.dataSource();

  // 初始化默认选择中国
  @override
  void onInit() {
    super.onInit();
  }

  // 选择头像
  void selectAvatar() {
    ResourcePickerSheet.show(onResult: (ResourcePickerResult result) async {
      if (result.isSuccess) {
        print('选择的文件路径: ${result.filePath}');
        ToastUtil.showLoading();
        final uploadRes = await AliyunOSSUploader.uploadAvatar(filePath: result.filePath!, userId: 'gluz_public_userid', onProgress: (int send, int total) {
          print('上传进度:${send.toDouble()/total.toDouble()}');
        });
        if (uploadRes.isSuccess) {
          if (uploadRes.url != null) {
            userAvatar.value = uploadRes.url!;
          }
          ToastUtil.dismiss();
        } else {
          ToastUtil.dismiss();
        }
      } else {
        print('选择失败: ${result.errorMessage}');
      }
    });
  }

  // 选择国籍
  void selectCountry() {

  }

  void onTapArea() {
    print('onTapArea');
    BottomModalSheet.showAreaSector((e) {
      areaEntity.value = e;
      areaTextEditController.text = areaEntity.value?.mergename ?? '';
    });
  }

  // 选择身份
  void selectIdentity(IdentityEntity identity) {
    selectedIdentity.value = identity;
  }

  // 提交表单
  Future<void> submitForm() async {
    if (companyName.value.isEmpty) {
      ToastUtil.show('请输入公司/个人名称'.tr);
      return;
    }
    
    if (areaEntity.value == null) {
      ToastUtil.show('请输入所在地区'.tr);
      return;
    }

    if (selectedIdentity.value == null) {
      ToastUtil.show('请选择身份'.tr);
      return;
    }

    print('提交表单数据:');
    print('公司名称: ${companyName.value}');
    print('头像: ${userAvatar.value}');
    print('国籍: ${loginController.selectedCountry.name}');
    print('地区: ${areaEntity.value?.mergename}');
    print('身份: ${selectedIdentity.value?.name}');


    ToastUtil.showLoading();
    String? faceImgUrl;
    String? filePath = await registerController.faceImageBase64String.saveToFile('face');
    if (filePath != null) {
      final uploadRes = await AliyunOSSUploader.uploadFile(filePath: filePath);
      if (uploadRes.isSuccess) {
        faceImgUrl = uploadRes.url;
      } else {
        ToastUtil.dismiss();
      }
    }

    ApiResponse? apiResponse = await app.http.request(path: '/api/user/register', method: Method.post, params: {
      'countryCode': loginController.selectedCountry.code,
      'phoneNumber': registerController.phoneController.text,
      'smsCode': registerController.verifyController.text,
      'faceImg': faceImgUrl,
      'password': registerController.pwdController.text,
      'nickName': companyName.value,
      'avatar': userAvatar.value ?? 'https://gluz-oss.oss-cn-beijing.aliyuncs.com/avatars/gluz_avatar.png',
      'country': loginController.selectedCountry.id.toString(),
      'areaId': areaEntity.value?.id.toString(),
      'identity': selectedIdentity.value?.id.toString(),
      'inviterCode': registerController.inviteController.text
    }, fromJson: (e) => ApiResponse.fromJson(e));

    if (apiResponse?.success == true) {
      ToastUtil.show('注册成功'.tr);
      LoginController loginController = Get.find<LoginController>();
      loginController.selectedCountry = loginController.selectedCountry;
      loginController.phoneController.text = registerController.phoneController.text;
      loginController.pwdController.text = registerController.pwdController.text;
      Get.back();
    }
  }
}
